package cn.boy.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 
 * @author Lucky
 *
 */
public class JdbcUtils {
	
	private static String url;
	private static String driverName;
	private static String username;
	private static String password;
	
	static{
		
		try {
			Properties prop = new Properties();
			InputStream is =JdbcUtils.class.getClassLoader().getResourceAsStream("config.properties");
			prop.load(is);
			//从配置文件中获取连接数据库所需的信息
			url = prop.getProperty("url");
			driverName = prop.getProperty("driverName");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			Class.forName(driverName);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	/**
	 * 获得数据库连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url, username, password);
	}
	/**
	 * 释放连接资源
	 * @param rs
	 * @param ps
	 * @param conn
	 */
	public static void free(ResultSet rs, PreparedStatement ps,Connection conn){

		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ps != null)
					ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
		}
	
		
		
	}
	
	
}
